package com.redis.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Objects;
import java.util.UUID;

@RestController
@RequestMapping("ms")
public class MiaoSha {

    @Resource
    private RedissonClient redissonClient;
    @Resource
    private StringRedisTemplate stringRedisTemplate;


    private String REDIS_KEY="pro:1";
    /**
     *秒杀
     * 1. redis 存 商品的数量   pro:1
     * 2. 查看商品的数量》0    购买 商品-1    添加uuid
     *
     */

    @PostMapping
    public void setVal(){
       stringRedisTemplate.opsForValue().set(REDIS_KEY,"10");
    }

    @GetMapping
    public void ms(){
        // 加锁
        RLock lock = redissonClient.getLock("pro001");
        try {
            lock.lock();
            // 逻辑
            int s = Integer.parseInt(Objects.requireNonNull(stringRedisTemplate.opsForValue().get(REDIS_KEY)));
            if(s>0){
                // 售卖商品
                System.out.println("1号服务售卖一件商品，还是有"+(s-1)+"件商品");
                stringRedisTemplate.opsForValue().decrement(REDIS_KEY);//
                stringRedisTemplate.opsForSet().add("userList", UUID.randomUUID().toString());
            }else{
                System.out.println("商品已经售卖完");
            }

        }catch (Exception e){

        }finally {
            lock.unlock();
        }


    }

}
